<?php

hc_core_ClassLoader::load('halo_IViewResolver');

hc_core_ClassLoader::load('halo_HttpRequest');
hc_core_ClassLoader::load('halo_HttpResponse');

hc_core_ClassLoader::load('hc_configuration_IConfiguration');

class halo_ConfigurationViewResolver implements halo_IViewResolver {
    protected $configuration;
    public function __construct(hc_configuration_IConfiguration $configuration) {
        $this->configuration = $configuration;
    }
    public function resolve($viewName, halo_HttpRequest $httpRequest, halo_HttpResponse $httpResponse) {

        $view = null;

        $coreViewConfig = $this->searchFor($viewName, array('(class)', 'url'));

        if ( array_key_exists('(class)', $coreViewConfig) ) {
            $viewClassName = $coreViewConfig['(class)'];
            $viewUrl = array_key_exists('url', $coreViewConfig) ? $coreViewConfig['url'] : null;
            hc_core_ClassLoader::load($viewClassName);
            $view = new $viewClassName($viewName, $viewUrl);
            $additionalConfigurationKeys = $view->getAdditionalConfigurationKeys();
            if ( $additionalConfigurationKeys and count($additionalConfigurationKeys) ) {
                foreach ( $this->searchFor($viewName, $additionalConfigurationKeys) as $key => $value ) {
                    $view->setAdditionalConfiguration($key, $value);
                }
            }
        }

        return $view;

    }
    protected function searchFor($viewName, array $searchItems) {

        $viewConfig = array();

        $stillLookingFor = array();

        foreach ( $searchItems as $searchItem ) {
            $stillLookingFor[$searchItem] = null;
        }

        $searchPaths = $this->generateSearchPaths($viewName);

        foreach ( $searchPaths as $path ) {
            foreach ( array_keys($stillLookingFor) as $config ) {

                $key = $path . '.' . $config;
                if ( $this->configuration->exists($key) ) {
                    $value = $this->configuration->get($key);
                    $viewConfig[$config] = $value;
                    unset($stillLookingFor[$config]);
                }

            }

            if ( count(array_keys($stillLookingFor)) == 0 ) {
                break;
            }

        }

        return $viewConfig;

    }
    protected function generateSearchPaths($viewName) {
        $viewNameParts = explode('.', $viewName);
        $searchPaths = array();
        while ( count($viewNameParts) > 0 ) {
            $searchPath = implode('.', $viewNameParts);
            array_pop($viewNameParts);
            array_push($searchPaths, $searchPath . '.__default');
            array_push($searchPaths, $searchPath);

        }
        array_push($searchPaths, '__default');
        array_push($searchPaths, '');
        return $searchPaths;
    }
}

?>
